package com.nus.servlets;

import com.nus.beans.Project;
import com.nus.beans.User;
import com.nus.database.ProjectsDBManager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/26/12
 * Time: 11:32 PM
 * To change this template use File | Settings | File Templates.
 */
public class ViewProjectInfoServlet extends AbstractServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        int projectId;
        Project project = null;
        String targetPage = null;
        String errorMessage = null;

        String projectIdParam = request.getParameter("projects");
        String projectIdAttr = (String) request.getAttribute("projects");

        if(projectIdAttr != null && !projectIdAttr.isEmpty()){
            projectIdParam = projectIdAttr;
            errorMessage = (String) request.getAttribute("ERROR_MESSAGE");
        }

        if (projectIdParam == null || projectIdParam.isEmpty()) {
            errorMessage = "Please select a project.";
            targetPage = "viewProjects.do";
        } else {
            projectId = Integer.parseInt(projectIdParam);
            Connection connection = getUserDatabaseConnection(request);
            ProjectsDBManager projectsDBManager = new ProjectsDBManager(connection);
            project = projectsDBManager.getProject(projectId);

            List<User> assignees = projectsDBManager.getProjectAssigneesList(projectId);
            List<User> allEligibleUsers = projectsDBManager.getUsersListForProjects();

            request.setAttribute("assigneesList", assignees);
            request.setAttribute("eligibleUser", allEligibleUsers);
            request.setAttribute("project", project);
            targetPage = (String) request.getAttribute("targetPage");
            if (targetPage == null) {
                targetPage = "/WEB-INF/project_info.jsp";
            }
            projectsDBManager.close();

        }
        request.setAttribute("ERROR_MESSAGE", errorMessage);

        RequestDispatcher dispatcher = request.getRequestDispatcher(targetPage);
        dispatcher.forward(request, response);

    }
}
